import redis
import demjson

try:
    import utils.config_util as config_util
except Exception:
    import config_util


def check_redis(host, port, password):
    """
    连接指定redis
    :param host: 主机名
    :param port: 端口号
    :param password: 密码
    :return: 指定redis的info信息
    """
    info = {}
    try:
        r = redis.StrictRedis(host=host, port=int(port), password=password, db=0, socket_timeout=3, charset='utf-8')
        info = {"server":_info_server(r),
            "clients":_info_clients(r),
            "memory":_info_memory(r),
            "persistence":_info_persistence(r),
            "stats":_info_stats(r),
            "replication":_info_replication(r),
            "cpu":_info_cpu(r),
            "cluster":_info_cluster(r),
            "keyspace":_info_keyspace(r)
            }
        return info
    except:
        return info


def _info_server(r):
    return r.info("server")


def _info_clients(r):
    return r.info("clients")


def _info_memory(r):
    return r.info("memory")


def _info_persistence(r):
    return r.info("persistence")


def _info_stats(r):
    return r.info("stats")


def _info_replication(r):
    info_replication = r.info("replication")
    if info_replication['role'] == 'master':
        info_replication['master_host'] = '-1'
        info_replication['master_port'] = '-1'
        info_replication['master_link_status'] = '-1'
        info_replication['master_last_io_seconds_ago'] = '-1'
        info_replication['master_sync_in_progress'] = '-1'
        info_replication['slave_priority'] = '-1'
        info_replication['slave_read_only'] = '-1'
    return info_replication


def _info_cpu(r):
    return r.info("cpu")


def _info_cluster(r):
    return r.info("cluster")


def _info_keyspace(r):
    return r.info("keyspace")


def check_local_redis():
    """
    读取本地redis的info信息
    redis的配置从配置文件中获取
    :return: 本地redis的info信息
    """
    host = config_util.get_config("redis", "host")
    port = config_util.get_config("redis", "port")
    password = config_util.get_config("redis", "password")
    return check_redis(host, port, password)


if __name__ == '__main__':
    host = config_util.get_config("redis", "host")
    port = config_util.get_config("redis", "port")
    password = config_util.get_config("redis", "password")
    info = check_redis(host, port, password)
    print(demjson.encode(info))
